<script setup>
import { ref } from 'vue'

// 输入框数据
const inputValue = ref()

// 下拉选择数据
const selectVue = ref([])

// 接收父组件的数据
const props = defineProps({
    tableDate: Array,
    subject: String
})

// 键盘输入事件
const searchSelect = () => {
    try {
        if (inputValue.value === '') {
        return selectVue.value = []
    }
    props.tableDate.forEach(item => {
       if (item.subject === props.subject && item.title.includes(inputValue.value)) {
        const result = selectVue.value.find(item2 => item2 === item.title)
        if (!result) {
            selectVue.value.push(item.title)
        }
       }
    })
    } catch (error) {
        console.log(error);
    }
}

// 下拉选项点击事件
const selectItem = (e) => {
    inputValue.value = e.target.innerText
    sendValue()
    selectVue.value = ''
}

// 子传父将输入框数据传过去
const emits = defineEmits(['input-value'])
const sendValue = () => {
    emits('input-value', inputValue.value)
}

// 使用defineExpose向父组件暴露清空输入框的方法
const delInput = () => {
    inputValue.value = '',
    selectVue.value = []
}
defineExpose({
    delInput
})
</script>

<template>
    <div class="query-input">
        <div class="input">
            <el-input v-model="inputValue" @input="searchSelect" style="width: 100%;"></el-input>
        </div>
        <div class="select" style="width: 100%;">
            <div @click="selectItem" class="item" v-for="(item, index) in selectVue" :key="index">{{ item }}</div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
    .query-input {
        // display: flex;
        position: relative;
        .select {
            position: absolute;
            top: 38px;
            background-color: #fff;
            z-index: 999;
            cursor: pointer;
            box-shadow: 0px 2px 10px #8e8e8e;
            text-indent: 1rem;
            .item {
                width: 100%;
                line-height: 40px;
                border-bottom: 1px solid rgb(202, 202, 202);
                &:hover{
                    background-color: #fafafa;
                }
            }
        }
    }
</style>